
package com.platform.modules.app.service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.github.binarywang.utils.qrcode.QrcodeUtils;
import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.bean.notify.WxPayRefundNotifyResult;
import com.github.binarywang.wxpay.bean.notify.WxScanPayNotifyResult;
import com.github.binarywang.wxpay.bean.order.WxPayMpOrderResult;
import com.github.binarywang.wxpay.bean.request.BaseWxPayRequest;
import com.github.binarywang.wxpay.bean.request.WxPayRefundRequest;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.bean.result.BaseWxPayResult;
import com.github.binarywang.wxpay.bean.result.WxPayRefundResult;
import com.github.binarywang.wxpay.bean.result.WxPayUnifiedOrderResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.platform.common.exception.BusinessException;
import com.platform.common.utils.CharUtil;
import com.platform.common.utils.Constant;
import com.platform.common.utils.RestResponse;
import com.platform.common.utils.StringUtils;
import com.platform.modules.mall.entity.*;
import com.platform.modules.mall.service.*;
import com.platform.modules.sys.service.MailService;
import com.thoughtworks.xstream.XStream;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.util.xml.XStreamInitializer;
import me.chanjar.weixin.mp.api.WxMpService;
import org.apache.commons.lang.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * @author
 */
@Slf4j
@Service("payService")
public class PayService {
    @Autowired
    private WxPayService wxPayService;
    @Autowired
    private WxMpService mpService;
    @Autowired
    private MallOrderService orderService;
    @Autowired
    private MallGoodsService goodsService;
    @Autowired
    private MallUserService userService;
    @Autowired
    private MallOrderGoodsService orderGoodsService;
    @Autowired
    private WxSendMsgService sendMsgService;
    @Autowired
    private MallAccountLogService accountLogService;
    @Autowired
    private MallUserIntegralLogService mallUserIntegralLogService;
    @Autowired
    private MailService mailService;
    @Autowired
    private MallCardSnService mallCardSnService;


    @Value("${wx.pay.baseNotifyUrl}")
    private String baseNotifyUrl;
    @Value("${wx.pay.spbillCreateIp}")
    private String spbillCreateIp;
    @Value("${qq.pay.mchId}")
    private String mchId;
    @Value("${qq.pay.mchKey}")
    private String mchKey;
    @Value("${qq.miniapp.appid}")
    private String appid;

    /**
     * 退款
     *
     * @param orderVo
     * @return
     */
    public RestResponse refund(MallOrderEntity orderVo) {
        // todo 需要退款，这里退款需要改，需要审核之后才能退款
        if (orderVo.getPayStatus().equals(Constant.PayStatus.YFK.getValue()) && Constant.PayType.WX.getValue().equals(orderVo.getPayType())) {
            try {
                //微信支付
                WxPayRefundRequest request = new WxPayRefundRequest();
                request.setOutTradeNo(orderVo.getOrderSn());
                request.setTotalFee(BaseWxPayRequest.yuanToFen(orderVo.getOrderPrice().toString()));
                request.setRefundFee(BaseWxPayRequest.yuanToFen(orderVo.getActualPrice().toString()));
                request.setOutRefundNo(StringUtils.getBundleId());
                request.setRefundDesc("用户取消订单");
                if (orderVo.getFromType().equals(Constant.FromType.MP.getValue())
                        || orderVo.getFromType().equals(Constant.FromType.MA.getValue())) {
                    WxPayRefundResult result = wxPayService.refund(request);
                    if (result.getResultCode().equals(Constant.SUCCESS)) {
                        if (orderVo.getOrderStatus().equals(Constant.OrderStatus.YFK.getValue())) {
                            orderVo.setOrderStatus(Constant.OrderStatus.TK.getValue());
                        } else if (orderVo.getOrderStatus().equals(Constant.OrderStatus.YFH.getValue())) {
                            orderVo.setOrderStatus(Constant.OrderStatus.THTK.getValue());
                        }
                        orderVo.setPayStatus(Constant.PayStatus.TK.getValue());
                        orderService.update(orderVo);

                        //取消订单释放商品库存
                        goodsService.backGoodsNumber(orderVo);
                        // 支付成功、 订单总金额(单位：分) 除以100保留两位小数
                        BigDecimal totalFee = new BigDecimal(result.getTotalFee()).divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);
                        MallUserEntity mallUserEntity = userService.getById(orderVo.getUserId());
                        // 退款减去购物积分
                        if (null != mallUserEntity) {
                            mallUserEntity.setSignAllIntegral(mallUserEntity.getSignAllIntegral().subtract(totalFee));
                            userService.update(mallUserEntity);
                        }
                        return RestResponse.success("取消成功！");
                    } else {
                        return RestResponse.error("取消成失败！");
                    }
                } else if (orderVo.getFromType().equals(Constant.FromType.ALI.getValue())) {
                    //todo 支付宝退款
                    return RestResponse.success("取消成功！");
                } else if (orderVo.getFromType().equals(Constant.FromType.QQ.getValue())) {
                    //todo QQ钱包退款
                    return RestResponse.success("取消成功！");
                } else {
                    //todo H5、APP退款
                    return RestResponse.success("取消成功！");
                }
            } catch (Exception e) {
                e.printStackTrace();
                throw new BusinessException("退款失败：" + e.getMessage());
            }
        } else {
            orderVo.setOrderStatus(Constant.OrderStatus.YQX.getValue());
            orderService.update(orderVo);
            //取消订单释放商品库存
            goodsService.backGoodsNumber(orderVo);
            return RestResponse.success("取消成功！");
        }
    }

    /**
     * 商品统一下单请求
     *
     * @param loginUser
     * @param jsonParam
     * @return
     */
    public RestResponse payPrepay(MallUserEntity loginUser, JSONObject jsonParam) {
        String orderId = jsonParam.getString("orderId");
        String tradeType = jsonParam.getString("tradeType");

        MallOrderEntity orderInfo = orderService.getById(orderId);
        if (null == orderInfo) {
            return RestResponse.error("订单已取消！");
        }
        if (!loginUser.getId().equals(orderInfo.getUserId())) {
            return RestResponse.error("非法操作！");
        }
        if (orderInfo.getPayStatus().equals(Constant.PayStatus.YFK.getValue())) {
            return RestResponse.error("订单已支付，请不要重复操作！");
        }

        Map<String, Object> orderGoodsParam = new HashMap<>(2);
        orderGoodsParam.put("orderId", orderId);
        //订单的商品
        List<MallOrderGoodsEntity> orderGoods = orderGoodsService.queryAll(orderGoodsParam);
        StringBuilder body = new StringBuilder();
        if (null != orderGoods && orderGoods.size() > 0) {
            for (MallOrderGoodsEntity goodsVo : orderGoods) {
                if (body.toString().getBytes(StandardCharsets.UTF_8).length < 90) {
                    body.append(goodsVo.getGoodsName()).append("*").append(goodsVo.getNumber()).append("、");
                } else {
                    body.append("...");
                }
            }
            if (body.length() > 0) {
                body = new StringBuilder(body.substring(0, body.length() - 1));
            }
        }
        Integer fromType = orderInfo.getFromType();

        try {
            WxPayMpOrderResult data = null;
            if (ObjectUtils.equals(fromType, Constant.FromType.MP.getValue())
                    || ObjectUtils.equals(orderInfo.getFromType(), Constant.FromType.MA.getValue())) {

                //调用统一下单接口，并组装生成支付所需参数对象
                WxPayUnifiedOrderRequest request = new WxPayUnifiedOrderRequest();
                request.setBody(body.toString());
                request.setOutTradeNo(orderInfo.getOrderSn());
                //支付金额
                request.setTotalFee(BaseWxPayRequest.yuanToFen(orderInfo.getActualPrice().toString()));
                request.setSpbillCreateIp(spbillCreateIp);
                request.setNotifyUrl(baseNotifyUrl + "/app/pay/notify");
                // 交易类型APP
                request.setTradeType(tradeType);
                request.setOpenid(loginUser.getOpenId());

                if (!ObjectUtils.equals(orderInfo.getActivityType(), "0")) {
                    request.setGoodsTag(orderInfo.getActivityType());
                }

                try {
                    data = wxPayService.createOrder(request);
                } catch (WxPayException e) {
                    e.printStackTrace();
                    /**
                     * 参考:微信支付出现OUT_TRADE_NO_USED:商户订单号重复
                     *
                     * 场景：使用微信支付，在微信支付界面，由于余额不足等原因，没有进行支付并关闭了支付页面，此时订单状态为“待支付”，从业务角度来说，应该允许用户继续支付。但是再次支付时，微信接口返回“201 商户订单号重复”的错误提示。
                     * 解决办法：待支付的订单号（即商户订单号，out_trade_no），再次支付时，务必保持商品描述字段和上次请求的内容完全一致。
                     * 　　　　另外，如果价格改变，也不能重复提交，只能重新生成订单号，重新向微信发起支付请求
                     * 这里如果客户下单后点击支付然后取消付款，在联系客服后台修改价格，用户再次下单就会产生此错误
                     * 这里处理方式是重新生成orderSn
                     */
                    if (e.getErrCodeDes().contains("商户订单号重复")) {
                        String productId = StringUtils.generateOrderNumber();
                        orderInfo.setOrderSn(productId);
                        orderService.update(orderInfo);

                        request.setOutTradeNo(productId);
                        data = wxPayService.createOrder(request);
                    }
                }
            }
            if (ObjectUtils.equals(orderInfo.getFromType(), Constant.FromType.QQ.getValue())) {
                //QQ钱包支付
                Map<Object, Object> request = new TreeMap<>();
                request.put("appid", appid);
                request.put("mch_id", mchId);
                // 商品描述
                request.put("body", body.toString());
                request.put("nonce_str", CharUtil.getRandomNum(18).toUpperCase());
                // 数字签证
                String sign = QqPayUtils.arraySign(request, mchKey);
                request.put("sign", sign);

                // 回调地址
                request.put("notify_url", baseNotifyUrl + "/app/pay/notify");
                request.put("out_trade_no", orderInfo.getOrderSn());
                request.put("spbill_create_ip", spbillCreateIp);
                //支付金额
                request.put("total_fee", BaseWxPayRequest.yuanToFen(orderInfo.getActualPrice().toString()));
                // 交易类型APP
                request.put("trade_type", tradeType);

                request.put("fee_type", "CNY");

                String xml = QqPayUtils.convertMap2Xml(request);
                String url = "https://qpay.qq.com/cgi-bin/pay/qpay_unified_order.cgi";

                String responseContent = wxPayService.post(url, xml, false);
                WxPayUnifiedOrderResult unifiedOrderResult = BaseWxPayResult.fromXML(responseContent, WxPayUnifiedOrderResult.class);

                //保存prepayId
                orderInfo.setPrepayId(unifiedOrderResult.getPrepayId());
                orderService.update(orderInfo);

                data = QqPayUtils.createOrder(unifiedOrderResult, request, mchKey);
            }
            return RestResponse.success().put("data", data);
        } catch (Exception e) {
            e.printStackTrace();
            return RestResponse.error("下单失败,error=" + e.getMessage());
        }
    }

    /**
     * 商品统一下单请求回调接口
     *
     * @param xmlData
     * @return
     */
    @Transactional(rollbackFor = Exception.class, isolation = Isolation.READ_UNCOMMITTED)
    public String notify(String xmlData) {
        try {
            WxPayOrderNotifyResult result = wxPayService.parseOrderNotifyResult(xmlData);
            String resultCode = result.getResultCode();
            String outTradeNo = result.getOutTradeNo();
            if (resultCode.equalsIgnoreCase(Constant.FAIL)) {
                // 订单编号
                log.error("订单" + outTradeNo + "支付失败");
                return setXml(Constant.SUCCESS, "OK");
            } else if (resultCode.equalsIgnoreCase(Constant.SUCCESS)) {
                // 订单编号
                log.error("订单" + outTradeNo + "支付成功");
                // 业务处理
                MallOrderEntity orderInfo = orderService.getOne(new QueryWrapper<MallOrderEntity>().eq("ORDER_SN", outTradeNo));
                // 已经支付,不再执行
                if (orderInfo.getPayStatus().equals(Constant.PayStatus.YFK.getValue())) {
                    return setXml(Constant.SUCCESS, "OK");
                }
                orderInfo.setPayType(Constant.PayType.WX.getValue());
                orderInfo.setPayStatus(Constant.PayStatus.YFK.getValue());
                orderInfo.setPayTime(new Date());
                if (orderInfo.getOrderStatus().equals(Constant.OrderStatus.DFK.getValue())) {
                    orderInfo.setOrderStatus(Constant.OrderStatus.YFK.getValue());
                }
                if (orderInfo.getOrderStatus().equals(Constant.OrderStatus.DXD.getValue())) {
                    orderInfo.setOrderStatus(Constant.OrderStatus.YFK.getValue());
                }

                // 实付金额
                Integer cashFee = result.getCashFee();
                // 优惠金额
                Integer couponFee = result.getCouponFee();
                //实付金额
                BigDecimal actualPrice = BigDecimal.valueOf(cashFee).divide(BigDecimal.valueOf(100));
                orderInfo.setActualPrice(actualPrice);
                orderInfo.setCouponPrice(couponFee == null ? BigDecimal.ZERO : BigDecimal.valueOf(couponFee).divide(BigDecimal.valueOf(100)));

                // 卡券订单需要发券
                if (orderInfo.getOrderType().compareTo(Constant.CARD_ORDER) == 0) {
                    //订单状态改为已付款未发货
                    orderInfo.setOrderStatus(Constant.OrderStatus.YFK.getValue());

                    orderInfo.setShippingStatus(Constant.ShippingStatus.WFH.getValue());
                    //不发券，通过定时任务发券 支付金额若大于我们的优惠之后的金额侧不发券进行退款

                    List<MallOrderGoodsEntity> list = orderGoodsService.list(new LambdaQueryWrapper<MallOrderGoodsEntity>()
                            .eq(MallOrderGoodsEntity::getOrderId, orderInfo.getId()));

//                    for (MallOrderGoodsEntity item : list) {
//                        MallGoodsEntity goods = goodsService.getById(item.getGoodsId());
//                        //活动价格
//                        BigDecimal unitPrice = goods.getUnitPrice();
//
//                        if(actualPrice.compareTo(unitPrice)==1){
//                            orderInfo.setOrderStatus(Constant.OrderStatus.TKSH.getValue());
//                        }
//                    }
//                    if (!mallCardSnService.sendCard(orderInfo)) {
//                        return setXml(Constant.FAIL, "卡券发送失败");
//                    }
                }

                // 支付成功、 订单总金额(单位：分) 除以100保留两位小数
                BigDecimal totalFee = orderInfo.getActualPrice().setScale(0,BigDecimal.ROUND_DOWN);
                // 低于一元不计入积分
                if(totalFee.intValue() >= 1){
                    // 用户积分增加记录
                    MallUserIntegralLogEntity entity = new MallUserIntegralLogEntity();
                    entity.setIntegral(orderInfo.getActualPrice().setScale(0,BigDecimal.ROUND_DOWN));
                    entity.setType(0);
                    entity.setUserId(orderInfo.getUserId());
                    entity.setDetails("商城购买");
                    mallUserIntegralLogService.integralChange(entity);
                    // 用户积分增加  与购物金额 1 : 1 增加
                    userService.lambdaUpdate()
                            .setSql("SIGN_ALL_INTEGRAL = IFNULL(SIGN_ALL_INTEGRAL,0) + " + totalFee)
                            .eq(MallUserEntity::getId,orderInfo.getUserId())
                            .update();
                }

                orderService.update(orderInfo);

                try {
                    // 微信通知
                    if (orderInfo.getFromType().equals(Constant.FromType.MA.getValue())) {
                        sendMsgService.notifyPaySuccess(orderInfo, Constant.STR_ONE);
                    } else if (orderInfo.getFromType().equals(Constant.FromType.MP.getValue())) {
                        //TODO 公众号下单，发送消息
                        MallUserEntity user = userService.getById(orderInfo.getUserId());
                        sendMsgService.sendUniformMsg(orderInfo,Constant.STR_ONE,user.getOpenId());
                    } else if (orderInfo.getFromType().equals(Constant.FromType.QQ.getValue())) {
                        //TODO QQ下单，发送消息
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                log.error("订单处理异常");
            }
            log.error("订单" + outTradeNo + "状态修改完成");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return setXml(Constant.SUCCESS, "OK");
    }

    /**
     * 余额支付（购买商品）
     *
     * @param loginUser
     * @param jsonParam
     * @return
     */
    public RestResponse buyByYue(MallUserEntity loginUser, JSONObject jsonParam) {
        String orderId = jsonParam.getString("orderId");
        Integer fromType = jsonParam.getInteger("fromType");

        MallOrderEntity orderInfo = orderService.getById(orderId);

        if (null == orderInfo) {
            return RestResponse.error("订单已取消！");
        }
        if (!loginUser.getId().equals(orderInfo.getUserId())) {
            return RestResponse.error("越权操作！");
        }

        if (orderInfo.getPayStatus().equals(Constant.PayStatus.YFK.getValue())) {
            return RestResponse.error("订单已支付，请不要重复操作！");
        }
        MallUserEntity malluserentity = userService.getById(orderInfo.getUserId());
        // 用户余额不足
        if (malluserentity.getBalance() == null || malluserentity.getBalance().doubleValue() < orderInfo.getActualPrice().doubleValue()) {
            return RestResponse.error(300, "用户余额不足！");
        } else {
            MallAccountLogEntity accountLogEntity = new MallAccountLogEntity();
            accountLogEntity.setLogDesc("余额支付");
            accountLogEntity.setUserId(loginUser.getId());
            accountLogEntity.setFromType(fromType);
            accountLogEntity.setType(2);
            accountLogEntity.setAddTime(new Date());
            accountLogEntity.setOrderType(Constant.NORMAL_ORDER);
            accountLogEntity.setPrice(orderInfo.getActualPrice());
            accountLogEntity.setOrderSn(StringUtils.generateOrderNumber());
            accountLogService.save(accountLogEntity);

            malluserentity.setBalance(malluserentity.getBalance().subtract(orderInfo.getActualPrice()));
            userService.update(malluserentity);
            // 业务处理
            // 已经支付,不再执行
            if (orderInfo.getPayStatus().equals(Constant.PayStatus.YFK.getValue())) {
                return RestResponse.success("支付成功！");
            }
            orderInfo.setPayType(Constant.PayType.YE.getValue());
            orderInfo.setPayStatus(Constant.PayStatus.YFK.getValue());
            orderInfo.setPayTime(new Date());
            if (orderInfo.getOrderStatus().equals(Constant.OrderStatus.DFK.getValue())) {
                orderInfo.setOrderStatus(Constant.OrderStatus.YFK.getValue());
            }
            if (orderInfo.getOrderStatus().equals(Constant.OrderStatus.DXD.getValue())) {
                orderInfo.setOrderStatus(Constant.OrderStatus.YFK.getValue());
            }
            if (orderInfo.getOrderStatus().equals(Constant.OrderStatus.YQX.getValue())) {
                orderInfo.setOrderStatus(Constant.OrderStatus.YFK.getValue());
            }
            if (Constant.SHOPS_ORDER.equals(orderInfo.getOrderType())) {
                orderInfo.setOrderStatus(Constant.OrderStatus.YFH.getValue());
                orderInfo.setShippingStatus(Constant.ShippingStatus.YFH.getValue());
            }
            orderService.update(orderInfo);
            return RestResponse.success("支付成功！");
        }
    }

    /**
     * 返回微信服务
     *
     * @param returnCode
     * @param returnMsg
     * @return
     */
    public String setXml(String returnCode, String returnMsg) {
        return "<xml><return_code><![CDATA[" + returnCode + "]]></return_code><return_msg><![CDATA[" + returnMsg + "]]></return_msg></xml>";
    }

    /**
     * 生成扫码支付二维码
     *
     * @return
     * @throws Exception
     */
    public byte[] generateQrCode() throws Exception {
        String productId = StringUtils.generateOrderNumber();

        String content = wxPayService.createScanPayQrcodeMode1(productId);
        String url = mpService.shortUrl(content);
        return QrcodeUtils.createQrcode(url, null);
    }

    /**
     * 扫码支付回调通知处理
     *
     * @param xmlData
     * @return
     */
    public Object parseScanPayNotifyResult(String xmlData) {
        try {
            final WxScanPayNotifyResult result = wxPayService.parseScanPayNotifyResult(xmlData);
            String productId = result.getProductId();
            MallOrderEntity orderInfo = orderService.getOne(new QueryWrapper<MallOrderEntity>().eq("ORDER_SN", productId));
            WxPayUnifiedOrderRequest request = new WxPayUnifiedOrderRequest();
            String goodsId = orderInfo.getGoodsId();
            MallGoodsEntity goods = goodsService.getById(goodsId);

            request.setBody(goods.getName() + orderInfo.getActualPrice() + "元");
            request.setOutTradeNo(productId);
            request.setProductId(productId);
            //支付金额
            request.setTotalFee(BaseWxPayRequest.yuanToFen(orderInfo.getActualPrice().toString()));
            request.setSpbillCreateIp(spbillCreateIp);
            // 回调地址
            request.setNotifyUrl(baseNotifyUrl + "/app/pay/parseOrderNotifyResult");
            // 交易类型APP
            request.setTradeType("NATIVE");
            request.setOpenid(result.getOpenid());

            //统一下单接口，在发起微信支付前，需要调用统一下单接口，获取"预支付交易会话标识"
            WxPayUnifiedOrderResult unifiedOrderResult = wxPayService.unifiedOrder(request);

            //记录prepayId
            orderInfo.setPrepayId(unifiedOrderResult.getPrepayId());
            orderService.update(orderInfo);

            XStream xstream = XStreamInitializer.getInstance();
            xstream.autodetectAnnotations(true);

            return unifiedOrderResult;
        } catch (WxPayException e) {
            e.printStackTrace();
        }
        return WxPayNotifyResponse.success("成功");
    }

    /**
     * 扫码支付结果
     *
     * @param xmlData
     * @return
     */
    public String parseOrderNotifyResult(String xmlData) {
        try {
            WxPayOrderNotifyResult result = wxPayService.parseOrderNotifyResult(xmlData);
            String resultCode = result.getResultCode();
            String outTradeNo = result.getOutTradeNo();
            if (resultCode.equalsIgnoreCase(Constant.FAIL)) {
                //订单编号
                log.info("扫码支付订单" + outTradeNo + "支付失败");
                return setXml(Constant.SUCCESS, "OK");
            } else if (resultCode.equalsIgnoreCase(Constant.SUCCESS)) {
                log.info("扫码支付订单" + outTradeNo + "支付成功");
                // 业务处理
                MallOrderEntity orderInfo = orderService.getOne(new QueryWrapper<MallOrderEntity>().eq("ORDER_SN", outTradeNo));
                // 已经支付,不再执行
                if (null == orderInfo || orderInfo.getPayStatus().equals(Constant.PayStatus.YFK.getValue())) {
                    return setXml(Constant.SUCCESS, "OK");
                }
                orderInfo.setPayStatus(Constant.PayStatus.YFK.getValue());
                orderInfo.setPayTime(new Date());
                if (orderInfo.getOrderStatus().equals(Constant.OrderStatus.DFK.getValue())) {
                    orderInfo.setOrderStatus(Constant.OrderStatus.YFK.getValue());
                }
                orderService.update(orderInfo);
            } else {
                log.error("扫码支付订单处理异常");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return setXml(Constant.SUCCESS, "OK");
    }

    public String parseRefundNotifyResult(String xmlData) {
        try {
            WxPayRefundNotifyResult result = this.wxPayService.parseRefundNotifyResult(xmlData);
            log.info("退款订单，result：" + result.toString());
            String returnCode = result.getReturnCode();
            String outTradeNo = result.getReqInfo().getOutTradeNo();
            //退款金额 分
            Integer refundFee = result.getReqInfo().getRefundFee();

            if (returnCode.equalsIgnoreCase(Constant.FAIL)) {
                //订单编号
                log.info("订单" + outTradeNo + "退款失败");
                return setXml(Constant.SUCCESS, "OK");
            } else if (returnCode.equalsIgnoreCase(Constant.SUCCESS)) {
                log.info("订单" + outTradeNo + "退款成功");
                // 业务处理
                MallOrderEntity orderInfo = orderService.getOne(new QueryWrapper<MallOrderEntity>().eq("ORDER_SN", outTradeNo));
                // 已经退款,不再执行
                if (null == orderInfo || orderInfo.getPayStatus().equals(Constant.PayStatus.TK.getValue())) {
                    return setXml(Constant.SUCCESS, "OK");
                }
                orderInfo.setPayStatus(Constant.PayStatus.TK.getValue());
                //订单已发货 退款
                if (orderInfo.getOrderStatus().equals(Constant.OrderStatus.YFH.getValue())) {
                    orderInfo.setOrderStatus(Constant.OrderStatus.THTK.getValue());
                } else {
                    //订单已收货 退款
                    orderInfo.setOrderStatus(Constant.OrderStatus.TK.getValue());
                }
                orderService.update(orderInfo);

                MallUserEntity malluserentity = userService.getById(orderInfo.getUserId());
                malluserentity.setBalance(malluserentity.getBalance().subtract(new BigDecimal(refundFee / 100)));
                userService.update(malluserentity);
            } else {
                log.error("订单退款处理异常");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return setXml(Constant.SUCCESS, "OK");
    }

    /**
     * 积分支付订单
     *
     * @param loginUser
     * @param jsonParam
     * @return
     */
    public RestResponse buyByIntegral(MallUserEntity loginUser, JSONObject jsonParam) {
        String orderId = jsonParam.getString("orderId");
        Integer fromType = jsonParam.getInteger("fromType");

        MallOrderEntity orderInfo = orderService.getById(orderId);

        if (null == orderInfo) {
            return RestResponse.error("订单已取消！");
        }
        if (!loginUser.getId().equals(orderInfo.getUserId())) {
            return RestResponse.error("越权操作！");
        }

        if (orderInfo.getPayStatus().equals(Constant.PayStatus.YFK.getValue())) {
            return RestResponse.error("订单已支付，请不要重复操作！");
        }
        MallUserEntity malluserentity = userService.getById(orderInfo.getUserId());
        // 用户余额不足
        if (malluserentity.getSignAllIntegral() == null || malluserentity.getSignAllIntegral().doubleValue() < orderInfo.getIntegralMoney().doubleValue()) {
            return RestResponse.error(300, "用户余额不足！");
        } else {
            // 记录用户积分扣除
            mallUserIntegralLogService.add(loginUser.getId(), orderInfo.getIntegralMoney(), loginUser.getSignAllIntegral()
                    , Constant.IntegralType.PAYOUT, "积分兑换商品");

            boolean flag = userService.update(new LambdaUpdateWrapper<MallUserEntity>()
                    .set(MallUserEntity::getSignAllIntegral, loginUser.getSignAllIntegral().subtract(orderInfo.getIntegralMoney()))
                    .set(MallUserEntity::getSignUsedIntegral, loginUser.getSignUsedIntegral().add(orderInfo.getIntegralMoney()))
                    .eq(MallUserEntity::getSignAllIntegral, loginUser.getSignAllIntegral())
                    .eq(MallUserEntity::getId, loginUser.getId())
            );
            if (!flag) {
                throw new BusinessException("系统繁忙请稍后重试");
            }
            // 业务处理
            // 已经支付,不再执行
            if (orderInfo.getPayStatus().equals(Constant.PayStatus.YFK.getValue())) {
                return RestResponse.success("支付成功！");
            }
            orderInfo.setPayType(Constant.PayType.YE.getValue());
            orderInfo.setPayStatus(Constant.PayStatus.YFK.getValue());
            orderInfo.setPayTime(new Date());
            if (orderInfo.getOrderStatus().equals(Constant.OrderStatus.DFK.getValue())) {
                orderInfo.setOrderStatus(Constant.OrderStatus.YFK.getValue());
            }
            if (orderInfo.getOrderStatus().equals(Constant.OrderStatus.DXD.getValue())) {
                orderInfo.setOrderStatus(Constant.OrderStatus.YFK.getValue());
            }
            if (orderInfo.getOrderStatus().equals(Constant.OrderStatus.YQX.getValue())) {
                orderInfo.setOrderStatus(Constant.OrderStatus.YFK.getValue());
            }
            if (Constant.SHOPS_ORDER.equals(orderInfo.getOrderType())) {
                orderInfo.setOrderStatus(Constant.OrderStatus.YFH.getValue());
                orderInfo.setShippingStatus(Constant.ShippingStatus.YFH.getValue());
            }
            orderService.update(orderInfo);
            return RestResponse.success("支付成功！");
        }
    }
}
